/*
 * @Author: yxfan
 * @Date: 2025-01-11 18:17:33
 * @LastEditTime: 2025-01-11 18:32:27
 * @FilePath: /umi-demo/src/components/CustomTree.jsx
 * @Description:
 */
import React, { useState, useEffect } from 'react';
import { Tree, Dropdown, Input } from 'antd';
import { EllipsisOutlined } from '@ant-design/icons';

const { Search } = Input;

const CustomTree = ({ treeData = [], onDelete, onEdit, onAdd }) => {
    const [hoveredNode, setHoveredNode] = useState(null);
    const [searchValue, setSearchValue] = useState('');
    const [expandedKeys, setExpandedKeys] = useState([]);
    const [filteredTreeData, setFilteredTreeData] = useState(treeData);

    const getNodeMenuItems = (node) => [
        {
            key: 'delete',
            label: '删除',
            onClick: () => onDelete?.(node),
        },
        {
            key: 'edit',
            label: '编辑',
            onClick: () => onEdit?.(node),
        },
        {
            key: 'add',
            label: '添加',
            onClick: () => onAdd?.(node),
        },
    ];

    // 获取节点的所有父节点key
    const getParentKeys = (node, nodes, parentKeys = []) => {
        for (const item of nodes) {
            if (item.children) {
                if (item.children.some((child) => child.key === node.key)) {
                    parentKeys.push(item.key);
                    getParentKeys(item, treeData, parentKeys);
                } else {
                    getParentKeys(node, item.children, parentKeys);
                }
            }
        }
        return parentKeys;
    };

    // 过滤树数据
    const filterTreeData = (data, searchText) => {
        if (!searchText) return data;

        const filtered = [];
        const expandKeys = new Set();

        const traverse = (nodes, parentMatched = false) => {
            return nodes
                .map((node) => {
                    const isMatch = node.title
                        .toLowerCase()
                        .includes(searchText.toLowerCase());
                    const children = node.children
                        ? traverse(node.children, isMatch)
                        : null;

                    if (isMatch) {
                        // 如果是叶子节点匹配
                        if (!node.children) {
                            // 获取并展开所有父节点
                            const parentKeys = getParentKeys(node, treeData);
                            parentKeys.forEach((key) => expandKeys.add(key));
                        }
                        return {
                            ...node,
                            children: children?.length ? children : undefined,
                        };
                    }

                    // 如果父节点匹配，返回节点但不展开子节点
                    if (parentMatched) {
                        return {
                            ...node,
                            children: undefined,
                        };
                    }

                    // 如果子节点有匹配，返回当前节点及匹配的子节点
                    if (children?.length) {
                        expandKeys.add(node.key);
                        return {
                            ...node,
                            children,
                        };
                    }

                    return null;
                })
                .filter(Boolean);
        };

        const result = traverse(data);
        setExpandedKeys([...expandKeys]);
        return result;
    };

    // 处理搜索
    const handleSearch = (value) => {
        setSearchValue(value);
        const filtered = filterTreeData(treeData, value);
        setFilteredTreeData(filtered);
    };

    const titleRender = (node) => {
        return (
            <div
                style={{ display: 'flex', alignItems: 'center', width: '100%' }}
                onMouseEnter={() => setHoveredNode(node.key)}
                onMouseLeave={() => setHoveredNode(null)}
            >
                <span style={{ flex: 1 }}>{node.title}</span>
                {hoveredNode === node.key && (
                    <Dropdown
                        menu={{ items: getNodeMenuItems(node) }}
                        trigger={['click']}
                        placement="bottomRight"
                    >
                        <EllipsisOutlined
                            style={{ marginLeft: 8, cursor: 'pointer' }}
                        />
                    </Dropdown>
                )}
            </div>
        );
    };

    // 初始化时设置过滤后的树数据
    useEffect(() => {
        setFilteredTreeData(treeData);
    }, [treeData]);

    // 处理节点展开/收起
    const handleExpand = (newExpandedKeys) => {
        setExpandedKeys(newExpandedKeys);
    };

    return (
        <div>
            <Search
                style={{ marginBottom: 8 }}
                placeholder="请输入搜索关键词"
                onChange={(e) => handleSearch(e.target.value)}
                allowClear
            />
            <Tree
                showLine
                expandedKeys={expandedKeys}
                onExpand={handleExpand}
                treeData={filteredTreeData}
                titleRender={titleRender}
            />
        </div>
    );
};

export default CustomTree;
